<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>{{ isEdit ? '编辑帮助文档' : '新增帮助文档' }}</span>
        </div>
      </template>
      
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入帮助文档标题" />
        </el-form-item>
        
        <el-form-item label="分类" prop="category">
          <el-select v-model="form.category" placeholder="请选择分类" style="width: 100%">
            <el-option
              v-for="item in categoryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="999" />
          <span class="form-tip">数字越小排序越靠前</span>
        </el-form-item>
        
        <el-form-item label="内容" prop="content">
          <WangEditor v-model="form.content" style="min-height:200px;" />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button type="success" @click="submitAndPublish">保存并发布</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { helpCenterApi } from '@/api/content'
import type { HelpCenter } from '@/types'
import WangEditor from '@/components/WangEditor.vue'

const route = useRoute()
const router = useRouter()
const formRef = ref<FormInstance>()
const loading = ref(false)

// 判断是编辑还是新增
const isEdit = computed(() => route.params.id !== undefined)

// 表单数据
const form = reactive<Partial<HelpCenter>>({
  title: '',
  content: '',
  category: 'account',
  sort: 1,
  status: 'draft',
  viewCount: 0
})

// 表单验证规则
const rules = reactive<FormRules>({
  title: [
    { required: true, message: '请输入帮助文档标题', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度在2到100个字符之间', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入帮助文档内容', trigger: 'blur' }
  ]
})

// 分类选项
const categoryOptions = [
  { value: 'account', label: '账户管理' },
  { value: 'order', label: '订单问题' },
  { value: 'product', label: '商品相关' },
  { value: 'shipping', label: '物流配送' },
  { value: 'payment', label: '支付问题' },
  { value: 'other', label: '其他问题' }
]

// 获取帮助文档详情
const getDetail = async (id: string) => {
  loading.value = true
  try {
    // 这里可以调用实际的API
    // const res = await helpCenterApi.getDetail(id)
    // Object.assign(form, res.data)
    
    // 模拟数据
    setTimeout(() => {
      const helpData: Record<string, HelpCenter> = {
        '1': {
          id: '1',
          title: '如何注册账号',
          content: '详细的账号注册流程说明...',
          category: 'account',
          status: 'published',
          sort: 1,
          viewCount: 1250,
          createTime: '2023-11-20 10:00:00',
          updateTime: '2023-11-20 10:00:00'
        },
        '2': {
          id: '2',
          title: '忘记密码怎么办',
          content: '密码找回流程及注意事项...',
          category: 'account',
          status: 'published',
          sort: 2,
          viewCount: 980,
          createTime: '2023-11-20 10:30:00',
          updateTime: '2023-11-20 10:30:00'
        }
      }
      
      if (helpData[id]) {
        Object.assign(form, helpData[id])
      } else {
        ElMessage.error('帮助文档不存在')
        router.push('/content/help')
      }
      
      loading.value = false
    }, 500)
  } catch (error) {
    console.error('获取帮助文档详情失败:', error)
    loading.value = false
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        if (isEdit.value) {
          // 编辑
          // await helpCenterApi.update(route.params.id as string, form)
          ElMessage.success('更新成功')
        } else {
          // 新增
          // await helpCenterApi.create(form)
          ElMessage.success('添加成功')
        }
        loading.value = false
        
        // 返回列表页
        router.push('/content/help')
      } catch (error) {
        console.error('保存帮助文档失败:', error)
        loading.value = false
        ElMessage.error('保存失败')
      }
    }
  })
}

// 保存并发布
const submitAndPublish = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      form.status = 'published'
      
      loading.value = true
      try {
        if (isEdit.value) {
          // 编辑
          // await helpCenterApi.update(route.params.id as string, form)
          ElMessage.success('更新并发布成功')
        } else {
          // 新增
          // await helpCenterApi.create(form)
          ElMessage.success('添加并发布成功')
        }
        loading.value = false
        
        // 返回列表页
        router.push('/content/help')
      } catch (error) {
        console.error('保存并发布帮助文档失败:', error)
        loading.value = false
        ElMessage.error('保存失败')
      }
    }
  })
}

// 取消
const cancel = () => {
  router.push('/content/help')
}

// 生命周期
onMounted(() => {
  // 如果是编辑模式，获取详情
  if (isEdit.value && route.params.id) {
    getDetail(route.params.id as string)
  }
})
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  span {
    font-size: 18px;
    font-weight: bold;
  }
}

.form-tip {
  margin-left: 10px;
  color: #909399;
  font-size: 13px;
}
</style> 